package Network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

//TCP实现的回显服务器的客户端
public class TcpEchoClient {
    private Socket socket = null;
    //1.构造函数传入目的服务器的Ip和端口号,和服务器建立连接
    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        //这样创建了TcpEchoClient对象就能够和服务器建立TCP连接
        socket = new Socket(serverIp,serverPort);
    }
    //2.start方法启动客户端，从控制太输入请求，并发送给服务器，接收服务器的响应，并打印到控制到
    private void start() throws IOException {
        System.out.println("客户端启动");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            while (true) {
                System.out.print("->");
                //接收控制台写入的请求,发送给服务器
                Scanner scanner = new Scanner(System.in);
                String request = scanner.next();
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                //刷新，确保请求全部发送出去
                printWriter.flush();
                //从服务器读取响应
                Scanner scannerServer = new Scanner(inputStream);
                String response = scannerServer.next();
                //在控制台打印响应
                System.out.println(response);
            }
        }finally {
            socket.close();//关闭文件
        }
    }
    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }
}
